"""
启动代码推荐服务的便捷脚本
"""

import os
import sys
import subprocess
import time
import signal
from pathlib import Path

def check_dependencies():
    """检查依赖是否安装"""
    required_packages = ['flask', 'flask_cors', 'neo4j', 'python-dotenv', 'requests']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n请运行以下命令安装:")
        print(f"pip install {' '.join(missing_packages)}")
        return False
    
    print("✅ 所有依赖包已安装")
    return True


def check_neo4j_connection():
    """检查Neo4j连接"""
    try:
        from scripts.code_recommender import get_driver
        
        driver = get_driver()
        with driver.session() as session:
            result = session.run("MATCH (f:Function) RETURN count(f) as count LIMIT 1")
            count = result.single()["count"]
            print(f"✅ Neo4j连接正常，数据库包含 {count} 个函数")
            driver.close()
            return True
    except Exception as e:
        print(f"❌ Neo4j连接失败: {e}")
        print("请确保:")
        print("1. Neo4j服务正在运行 (默认端口 7687)")
        print("2. 已导入调用关系数据")
        print("3. 环境变量配置正确")
        return False


def start_api_service():
    """启动API服务"""
    print("\n🚀 启动代码推荐API服务...")
    
    # 设置环境变量
    env = os.environ.copy()
    env['API_HOST'] = '0.0.0.0'
    env['API_PORT'] = '5000'
    env['API_DEBUG'] = 'True'
    
    # 启动Flask应用
    script_path = Path(__file__).parent / "recommendation_api.py"
    
    try:
        process = subprocess.Popen([
            sys.executable, str(script_path)
        ], env=env)
        
        print("✅ API服务已启动")
        print("📡 服务地址: http://localhost:5000")
        print("📋 API文档:")
        print("   - 健康检查: GET /health")
        print("   - 函数推荐: POST /recommendations/function")
        print("   - 下一个调用: POST /recommendations/next-calls")
        print("   - 搜索函数: POST /search/functions")
        print("   - 数据库统计: GET /stats")
        print("\n按 Ctrl+C 停止服务")
        
        # 等待进程结束
        process.wait()
        
    except KeyboardInterrupt:
        print("\n🛑 正在停止服务...")
        process.terminate()
        process.wait()
        print("✅ 服务已停止")
    except Exception as e:
        print(f"❌ 启动服务失败: {e}")


def run_demo():
    """运行演示"""
    print("\n🎯 运行代码推荐演示...")
    
    script_path = Path(__file__).parent / "demo_recommendations.py"
    
    try:
        subprocess.run([sys.executable, str(script_path)])
    except Exception as e:
        print(f"❌ 运行演示失败: {e}")


def show_menu():
    """显示菜单"""
    print("\n" + "="*50)
    print("🎯 Neo4j代码推荐系统")
    print("="*50)
    print("1. 启动API服务")
    print("2. 运行演示")
    print("3. 检查系统状态")
    print("4. 退出")
    print("-"*50)


def main():
    """主函数"""
    print("🚀 Neo4j代码推荐系统启动器")
    
    while True:
        show_menu()
        
        try:
            choice = input("请选择操作 (1-4): ").strip()
            
            if choice == '1':
                if check_dependencies() and check_neo4j_connection():
                    start_api_service()
                else:
                    print("❌ 系统检查失败，无法启动服务")
            
            elif choice == '2':
                if check_dependencies() and check_neo4j_connection():
                    run_demo()
                else:
                    print("❌ 系统检查失败，无法运行演示")
            
            elif choice == '3':
                print("\n🔍 检查系统状态...")
                deps_ok = check_dependencies()
                neo4j_ok = check_neo4j_connection()
                
                if deps_ok and neo4j_ok:
                    print("✅ 系统状态正常，可以启动服务")
                else:
                    print("❌ 系统状态异常，请检查配置")
            
            elif choice == '4':
                print("👋 再见！")
                break
            
            else:
                print("❌ 无效选择，请输入 1-4")
        
        except KeyboardInterrupt:
            print("\n👋 再见！")
            break
        except Exception as e:
            print(f"❌ 操作失败: {e}")


if __name__ == "__main__":
    main()
